package zzhyc.keystore

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
import com.kwad.sdk.api.KsAdSDK
import com.kwad.sdk.api.KsAdVideoPlayConfig
import com.kwad.sdk.api.KsFeedAd
import com.kwad.sdk.api.KsFullScreenVideoAd
import com.kwad.sdk.api.KsInnerAd
import com.kwad.sdk.api.KsInterstitialAd
import com.kwad.sdk.api.KsLoadManager
import com.kwad.sdk.api.KsLoadManager.FeedAdListener
import com.kwad.sdk.api.KsLoadManager.InterstitialAdListener
import com.kwad.sdk.api.KsRewardVideoAd
import com.kwad.sdk.api.KsScene
import com.kwad.sdk.api.KsVideoPlayConfig
import com.kwad.sdk.api.model.RewardTaskType
import zzhyc.keystore.databinding.ActivityShouKuaiInfoBinding

private const val TAG = "ShouKuaiInfoActivity"

class ShouKuaiInfoActivity : AppCompatActivity() {

    private val binding by lazy { ActivityShouKuaiInfoBinding.inflate(layoutInflater) }
    private var logStr = StringBuilder()

    companion object {
        const val SBLOGS = "sblogs"
        fun startActivity(context: Context, logs: String) {
            val intent = Intent(context, ShouKuaiInfoActivity::class.java)
            intent.putExtra(SBLOGS, logs)
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        getIntentParams()
        //激励
        binding.ksInfoBtnJiLi.setOnClickListener {
            initJiLi()
        }

        //插屏
        binding.ksInfoBtnCha.setOnClickListener {
            initCha()
        }
        //信息流
        binding.ksInfoBtnDraw.setOnClickListener {
            startActivityForResult(Intent(this, ShouKuaiDrawActivity::class.java), 101)
        }

        //全屏广告
        binding.ksInfoBtnScreen.setOnClickListener {
            initScreenVideo()
        }

        initBanner()
    }

    private fun getIntentParams() {
        intent.extras?.let {
            it.getString(SBLOGS)?.let { mLog ->
                setLogsView(mLog)
            }
        }
    }

    private fun initScreenVideo() {
        val ksScene = KsScene.Builder(ShouKuaiKey.KS_SCREEN_ID).build()
        KsAdSDK.getLoadManager()
            .loadFullScreenVideoAd(ksScene, object : KsLoadManager.FullScreenVideoAdListener {
                override fun onError(p0: Int, p1: String?) {
                    setLogsView("快手全屏广告/onError: ${p0}，msg-- ${p1} \n")
                }

                override fun onFullScreenVideoResult(p0: MutableList<KsFullScreenVideoAd>?) {
                    setLogsView("快手全屏广告/onFullScreenVideoResult: 全屏视频广告数据请求成功 \n")
                }

                override fun onFullScreenVideoAdLoad(p0: MutableList<KsFullScreenVideoAd>?) {
                    if (p0 == null || p0.isEmpty()) return
                    setLogsView(
                        "快手全屏广告/onFullScreenVideoAdLoad: 全屏视频广告数据请求且资源缓存成功 \n"
                    )
                    val fullScreen = p0[0]
                    fullScreen.setFullScreenVideoAdInteractionListener(
                        object : KsFullScreenVideoAd.FullScreenVideoAdInteractionListener {
                            override fun onAdClicked() {
                                setLogsView(
                                    "快手全屏广告/onAdClicked: 全屏视频广告点击，价格为-- ${fullScreen.ecpm} \n"
                                )
                            }

                            override fun onPageDismiss() {
                                setLogsView(
                                    "快手全屏广告/onPageDismiss: 全屏视频广告关闭，价格为-- ${fullScreen.ecpm} \n"
                                )
                            }

                            override fun onVideoPlayError(p0: Int, p1: Int) {
                                setLogsView("快手全屏广告/onVideoPlayError: ${p0}，msg-- ${p1} \n")
                            }

                            override fun onVideoPlayEnd() {
                                setLogsView("快手全屏广告/onVideoPlayEnd: 全屏视频广告播放完成 \n")
                            }

                            override fun onVideoPlayStart() {
                                setLogsView("快手全屏广告/onVideoPlayStart: 全屏视频广告播放开始 \n")
                            }

                            override fun onSkippedVideo() {
                                setLogsView("快手全屏广告/onSkippedVideo: 全屏视频广告播放跳过 \n")
                            }
                        })
                    val playConfig = KsVideoPlayConfig.Builder().build()
                    fullScreen.showFullScreenVideoAd(this@ShouKuaiInfoActivity, playConfig)
                }
            })
    }

    private fun initBanner() {
        val ksScene =
            KsScene.Builder(ShouKuaiKey.KS_BANNER_ID)
                .width(binding.ksInfoBanner.width)
                .adNum(1)   //一次加载一个
                .build()
        KsAdSDK.getLoadManager().loadConfigFeedAd(ksScene, object : FeedAdListener {
            override fun onError(p0: Int, p1: String?) {
                setLogsView("快手banner/onError: ${p0}，msg--  ${p1} \n")
            }

            override fun onFeedAdLoad(p0: MutableList<KsFeedAd>?) {
                setLogsView("快手banner/onFeedAdLoad: \n")
                if (p0 == null || p0.isEmpty()) return
                val bannerView = p0[0]
                bannerView.setAdInteractionListener(object : KsFeedAd.AdInteractionListener {
                    override fun onAdClicked() {
                        setLogsView("快手banner/onAdClicked: 广告点击回调 \n")
                    }

                    override fun onAdShow() {
                        setLogsView("快手banner/onAdShow: 广告曝光回调 \n")
                    }

                    override fun onDislikeClicked() {
                        setLogsView("快手banner/onDislikeClicked: 广告不喜欢回调 \n")
                    }

                    override fun onDownloadTipsDialogShow() {
                        setLogsView("快手banner/onDownloadTipsDialogShow: 广告展示下载合规弹窗 \n")
                    }

                    override fun onDownloadTipsDialogDismiss() {
                        setLogsView("快手banner/onDownloadTipsDialogDismiss: 广告关闭下载合规弹窗 \n")
                    }
                })
                val playConfig = KsAdVideoPlayConfig.Builder().build()
                bannerView.setVideoPlayConfig(playConfig)
                bannerView.render(object : KsFeedAd.AdRenderListener {
                    override fun onAdRenderSuccess(p0: View?) {
                        setLogsView("快手banner/onAdRenderSuccess: 价格为-- ${bannerView.ecpm} 分 \n")
                        val videoView = bannerView.getFeedView(this@ShouKuaiInfoActivity)
                        if (videoView != null && videoView.getParent() == null) {
                            binding.ksInfoBanner.removeAllViews()
                            binding.ksInfoBanner.addView(videoView)
                        }
                    }

                    override fun onAdRenderFailed(p0: Int, p1: String?) {
                        setLogsView("快手banner/onAdRenderFailed: ${p0}，msg-- ${p1} \n")
                    }
                })
            }
        })
    }

    private fun initCha() {
        val ksScene = KsScene.Builder(ShouKuaiKey.KS_CHA_ID).build()
        KsAdSDK.getLoadManager().loadInterstitialAd(ksScene, object : InterstitialAdListener {
            override fun onError(p0: Int, p1: String?) {
                setLogsView("快手插屏/onError: ${p0}，msg-- ${p1} \n")
            }

            override fun onRequestResult(p0: Int) {
                setLogsView("快手插屏/onRequestResult/插屏广告请求填充个数: ${p0} \n")
            }

            override fun onInterstitialAdLoad(p0: MutableList<KsInterstitialAd>?) {
                setLogsView("快手插屏/onInterstitialAdLoad/插屏广告请求成功:  \n")
                if (p0 == null || p0.isEmpty()) return
                val chaView = p0[0]
                val playConfig = KsVideoPlayConfig.Builder().build()
                chaView.setAdInteractionListener(object : KsInterstitialAd.AdInteractionListener {
                    override fun onAdClicked() {
                        setLogsView("快手插屏/onAdClicked/插屏广告点击:  \n")
                    }

                    override fun onAdShow() {
                        setLogsView("快手插屏/onAdShow:  \n")
                    }

                    override fun onAdClosed() {
                        setLogsView(
                            "快手插屏/onAdClosed/用户点击插屏关闭按钮/价格为: ${chaView.ecpm} 分 \n"
                        )
                    }

                    override fun onPageDismiss() {
                        setLogsView("快手插屏/onPageDismiss/插屏广告关闭/价格为: ${chaView.ecpm} 分 \n")
                    }

                    override fun onVideoPlayError(p0: Int, p1: Int) {
                        setLogsView("快手插屏/onVideoPlayError: ${p0}，-- ${p1} \n")
                    }

                    override fun onVideoPlayEnd() {
                        setLogsView("快手插屏/onVideoPlayEnd/插屏广告播放完成:  \n")
                    }

                    override fun onVideoPlayStart() {
                        setLogsView("快手插屏/onVideoPlayStart/插屏广告播放开始:  \n")
                    }

                    override fun onSkippedAd() {
                        setLogsView("快手插屏/onSkippedAd/插屏广告播放跳过/价格为: ${chaView.ecpm} \n")
                    }
                })

                chaView.showInterstitialAd(this@ShouKuaiInfoActivity, playConfig)
            }
        })
    }

    private fun initJiLi() {
        val ksScene = KsScene.Builder(ShouKuaiKey.KS_JILI_ID).build()
        KsAdSDK.getLoadManager().loadRewardVideoAd(ksScene, object :
            KsLoadManager.RewardVideoAdListener {
            override fun onError(p0: Int, p1: String?) {
                setLogsView("快手激励视频/onError: ${p0}，msg-- ${p1} \n")
            }

            override fun onRewardVideoResult(p0: MutableList<KsRewardVideoAd>?) {
                setLogsView("快手激励视频/onRewardVideoResult：激励视频广告数据请求成功 \n")
            }

            override fun onRewardVideoAdLoad(p0: MutableList<KsRewardVideoAd>?) {
                setLogsView(
                    "快手激励视频/onRewardVideoAdLoad/激励视频广告数据请求且资源缓存成功: ${p0?.size} \n"
                )
                if (p0 == null || p0.isEmpty()) return
                val rewardView = p0[0]
                rewardView.setRewardAdInteractionListener(object :
                    KsRewardVideoAd.RewardAdInteractionListener {
                    override fun onAdClicked() {
                        setLogsView("快手激励视频/onAdClicked: 激励视频广告点击 \n")
                    }

                    override fun onPageDismiss() {
                        setLogsView(
                            "快手激励视频/onPageDismiss: 激励视频广告关闭，价格为--- ${rewardView.ecpm} 分 \n"
                        )
                    }

                    override fun onVideoPlayError(p0: Int, p1: Int) {
                        setLogsView("快手激励视频/onVideoPlayError: ${p0}，extra-- ${p1} \n")
                    }

                    override fun onVideoPlayEnd() {
                        setLogsView("快手激励视频/onVideoPlayEnd: 激励视频广告播放完成 \n")
                    }

                    override fun onVideoSkipToEnd(p0: Long) {
                        setLogsView("快手激励视频/onVideoSkipToEnd：激励视频广告跳过播放完成 \n")
                    }

                    override fun onVideoPlayStart() {
                        setLogsView("快手激励视频/onVideoPlayStart: \n")
                    }

                    override fun onRewardVerify() {
                        setLogsView("快手激励视频/onRewardVerify：激励视频广告获取激励 \n")
                    }

                    override fun onRewardVerify(p0: MutableMap<String, Any>?) {
                        setLogsView("onRewardVerify/激励视频广告获取激励: ${Gson().toJson(p0)} \n")
                    }

                    override fun onRewardStepVerify(p0: Int, p1: Int) {
                        setLogsView(
                            "快手激励视频/onRewardStepVerify/激励视频广告分阶段获取激励，当前任务类型为: ${
                                getTaskStatusStr(p0)
                            }，当前完成任务类型为：${getTaskStatusStr(p1)}，价格为-- ${rewardView.ecpm}分 \n"
                        )
                    }

                    override fun onExtraRewardVerify(p0: Int) {
                        setLogsView(
                            "快手激励视频/onExtraRewardVerify/激励视频广告获取额外奖励: ${
                                getTaskStatusStr(p0)
                            } \n"
                        )
                    }
                })

                rewardView.setInnerAdInteractionListener(object :
                    KsInnerAd.KsInnerAdInteractionListener {
                    override fun onAdClicked(p0: KsInnerAd?) {
                        setLogsView("快手激励视频/onAdClicked: 激励视频内部广告点击 \n")
                    }

                    override fun onAdShow(p0: KsInnerAd?) {
                        setLogsView("快手激励视频/onAdShow: 激励视频内部广告曝光 \n")
                    }
                })

                val playConfig = KsVideoPlayConfig.Builder().build()
                rewardView.showRewardVideoAd(this@ShouKuaiInfoActivity, playConfig)
            }
        })
    }

    private fun getTaskStatusStr(taskType: Int): String {
        var taskStatusStr = ""
        when (taskType) {
            RewardTaskType.LOOK_VIDEO -> taskStatusStr = "观看视频"
            RewardTaskType.LOOK_LANDING_PAGE -> taskStatusStr = "浏览落地页"
            RewardTaskType.USE_APP -> taskStatusStr = "使用APP"
        }
        return taskStatusStr
    }

    /**
     *  将所有的日志显示到textView上
     */
    private fun setLogsView(logs: String) {
        Log.i(TAG, logs)
        logStr.append(logs)
        if (logStr.isNotEmpty()) {
            binding.ksInfoTvLog.text = logStr.toString()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 101 && resultCode == RESULT_OK) {
            data?.getStringExtra("drawLogs")?.let { appendLog ->
                logStr.append(appendLog)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        logStr.setLength(0) //重制到初始状态
    }

    private var mExitTime: Long = 0
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - mExitTime > 2000) {
                Toast.makeText(this, getString(R.string.exit_program), Toast.LENGTH_SHORT).show()
                mExitTime = System.currentTimeMillis()
            } else {
                if (!this.isFinishing) {
                    finishAndRemoveTask()
                }
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }
}